package com.company.common.poi;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.Map;
import java.util.UUID;

public class DocumentHandler {
    public static InputStream createWord(Map<?, ?> map,Class c,String templateName) {
        InputStream inputStream = null;
        try {
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
            configuration.setDefaultEncoding("UTF-8");
            // ftl模板文件
            configuration.setClassLoaderForTemplateLoading(c.getClassLoader(),"/templates");
            // 获取模板
            Template template = configuration.getTemplate(templateName);
            File outFile = File.createTempFile("temp"+ UUID.randomUUID().toString(), ".doc");
            outFile.deleteOnExit();
            // 将模板和数据模型合并生成文件
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
            // 生成文件
            template.process(map,out);
            out.flush();
            out.close();
            inputStream = new FileInputStream(outFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputStream;
    }


    public static InputStream createExcle(Map<?, ?> map,Class c,String templateName) {
        InputStream inputStream = null;
        try {
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
            configuration.setDefaultEncoding("UTF-8");
            // ftl模板文件
            configuration.setClassLoaderForTemplateLoading(c.getClassLoader(),"/templates");
            // 获取模板
            Template template = configuration.getTemplate(templateName);
            File outFile = File.createTempFile("temp"+ UUID.randomUUID().toString(), ".xls");
            outFile.deleteOnExit();
            // 将模板和数据模型合并生成文件
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
            // 生成文件
            template.process(map,out);
            out.flush();
            out.close();
            inputStream = new FileInputStream(outFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputStream;
    }
}
